package top.zhangjianyong.tools.timer;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import top.zhangjianyong.tools.annotation.DoTimer;
import top.zhangjianyong.tools.entity.ETF;
import top.zhangjianyong.tools.model.ETFMedianInfo;
import top.zhangjianyong.tools.service.mybatis.IETFDataService;
import top.zhangjianyong.tools.service.mybatis.IETFService;
import top.zhangjianyong.tools.utils.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author ： zhangjianyong
 * @date ： 2022/11/17 2:39 PM
 */
@Slf4j
@Component
public class ETFMedianTimer {
    private final static String EMAIL = "605600162@qq.com";
    @Autowired
    private IETFDataService ietfDataService;
    @Autowired
    private IETFService ietfService;
    @Autowired
    private ETFMedianUtil etfMedianUtil;
    @Autowired
    private HolidayUtil holidayUtil;

    @Value("${timer-flag}")
    private Boolean timerFlag;


    //@Scheduled(cron = "0 45 14 * * ?")
    @DoTimer(dateType = 1)
    public void timerEnd() {
        try {
            doTimer();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            try {
                MailUtil.send(EMAIL, "ETF统计：异常", ExceptionUtil.getExceptionToString(e));
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex);
            }
        }

    }

    public void doTimer() {
        //取三个个交易日时间
        List<LocalDate> dates = holidayUtil.lastStock(LocalDate.now(), 3);
        log.info("检查交易日：{}", dates);
        //查询所有
        List<ETF> list = ietfService.listNotDel();
        /*Set<String> codeSet = ietfDataService.listEtf().stream()
                .map(m -> m.get("code")).collect(Collectors.toSet());*/
        Set<String> codeSet = list.stream().map(ETF::getCode).collect(Collectors.toSet());
        //检查数据完整
        String code = etfMedianUtil.checkDateFail(codeSet, dates);
        if (StrUtil.isNotBlank(code)) {
            throw new RuntimeException("历史数据未更新，请检查: " + code);
        }

        List<ETFMedianInfo> medianInfos = list.stream().map(etf -> {
            ETFMedianInfo avgInfo = etfMedianUtil.etfMedianInfo(etf);
            return avgInfo;
        }).collect(Collectors.toList());

        String hc = medianInfos.stream().filter(info -> info.getHcf().compareTo(new BigDecimal(-10)) < 0)
            .sorted((Comparator.comparing(ETFMedianInfo::getHcf)))
            .map(this::infoToString)
            .collect(Collectors.joining("\n"));

        String ssf10 = medianInfos.stream().filter(info ->
                info.getSsf().compareTo(new BigDecimal(10)) >= 0)
            .sorted(Comparator.comparing(ETFMedianInfo::getPosition))
            .map(this::infoToString)
            .collect(Collectors.joining("\n"));

        String ssf5 = medianInfos.stream().filter(info ->
                info.getSsf().compareTo(new BigDecimal(5)) > 0
                    && info.getSsf().compareTo(new BigDecimal(10)) < 0)
            .sorted(Comparator.comparing(ETFMedianInfo::getPosition))
            .map(this::infoToString)
            .collect(Collectors.joining("\n"));

        StringBuilder message = new StringBuilder();
      /*  if (StringUtils.isNotBlank(hc)) {
            message.append("【回撤】\n");
            message.append(hc);
            message.append("\n");
        }*/
        if (StringUtils.isNotBlank(ssf10)) {
            message.append("【上升10】\n");
            message.append(ssf10);
        }
        if (StringUtils.isNotBlank(ssf5)) {
            message.append("【上升5】\n");
            message.append(ssf5);
        }


        //邮件

        try {
            MailUtil.send(EMAIL, "ETF统计:一个月内", message.toString());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }

    }

    public String infoToString(ETFMedianInfo info) {
        StringBuildUtil sb = new StringBuildUtil();
        sb.append("---------------- \n");
        sb.append("编码: {} \n", info.getCode());
        sb.append("名字: {} \n", info.getName());
        sb.append("时间: {} \n", info.getDateTime().toString());
        sb.append("类型: {} \n", info.getType());
        sb.append("涨跌幅: {} \n", info.getZdf().toString());
        sb.append("回撤幅: {} \n", info.getHcf().toString());
        sb.append("上升幅: {} \n", info.getSsf().toString());
        sb.append("位置: {} \n", info.getPosition().toString());
        return sb.getString();
    }

}
